#include <stdio.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <mysql.h>
#include <unistd.h>
int main()
{
	int ret = 0;

	fd = socket(AF_INET, SOCK_STREAM, 0); 
	if(fd < 0) {
		perror("socket");
		return 1;
	} 


	struct sockaddr_in dst;
	dst.sin_family = AF_INET;
	dst.sin_port = htons(12211);
	dst.sin_addr.s_addr = htonl(INADDR_ANY);
	int one = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(dst));


	MYSQL tmp;
        MYSQL *my = NULL;
        my = mysql_init(&tmp);
        int *r = NULL;
        r = mysql_real_connect(my, "localhost", "root", "MzYj@123456", "nbiot", 0, NULL, 0);
        if(r == NULL) {
        printf("mysql real connect error\n");
                return 1;
        }
	
	ret = bind(fd, &dst, 16);
	if(ret < 0) {
		perror("bind");
		return 1;
	} 

	ret = listen(fd, 20);
	if(ret < 0) {
		perror("listen");
		return 1;
	}
	
	struct sockaddr_in clt;
	int clt_len = 0;
	int nfd = accept(fd, &clt, &clt_len);
	if(nfd < 0) {
		perror("accept");
		return 1;
	
	}
	
	while(1){
                char *sql = "select * from nbiot ";
                int value = 0;
                value = mysql_query(my, sql);
                if(value != 0) {
                        printf("mysql query\n");
                        return 1;
                }



                MYSQL_RES *res = NULL;
                res = mysql_store_result(my);
                MYSQL_ROW row;
                row = mysql_fetch_row(res);


                char *b = row[1];
		//sleep(1);
                usleep(1000000);
		int ret = 0;
                ret = send(nfd,b,22,0);
                if(ret<0){
                        perror("sendto");
			return 0;
                }else{
                	printf(b);
               		printf("\n");
		}
                }
        }
